package com.starryx.driverschool.service.impl;

import com.starryx.driverschool.dao.AccountRepository;
import com.starryx.driverschool.po.Account;
import com.starryx.driverschool.po.Student;
import com.starryx.driverschool.service.AccountService;
import com.starryx.driverschool.vo.AccountQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountRepository accountRepository;


    @Override
    public Page<Account> listAccount(Pageable pageable) {
        return accountRepository.findAll(pageable);
    }

    @Override
    public Page<Account> listAccount(Pageable pageable, AccountQuery accountQuery) {
        return accountRepository.findAll(new Specification<Account>() {
            @Override
            public Predicate toPredicate(Root<Account> root,       // 相当于表名
                                         CriteriaQuery<?> cq,   // 条件查询执行器
                                         CriteriaBuilder cb) {  // 条件语句构建器，用于定义查询条件
                List<Predicate> predicates = new ArrayList<>();     // 查询条件组
                if (!"".equals(accountQuery.getName()) && accountQuery.getName() != null) {
                    predicates.add(cb.like(root.<Student>get("student").<String>get("name"), "%" + accountQuery.getName() + "%"));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));     // 将条件构造器构建的查询条件放到执行器执行
                return null;
            }
        }, pageable);
    }

    @Transactional
    @Override
    public Account saveAccount(Account account) {
        account.setCreateTime(new Date());
        return accountRepository.save(account);
    }

    @Override
    public Account getAccount(Long id) {
        return accountRepository.findOne(id);
    }

    @Transactional
    @Override
    public void deleteAccount(Long id) {
        accountRepository.delete(id);
    }
}
